#ecoding: utf-8 -*-
from quixote.directory import Directory
from quixote.publish import Publisher
from quixote.errors import PublishError

class PynixWebController(Directory):
    def __init__(self):
        self.messages = []
        self._q_exports.append('')
        for method in dir(self):
            if(not method.startswith("_")):
                self._q_exports.append(method)
    def _q_index(self):
        return self.index()
    
    def index(self):
        pass
    
#fireweb使用不到rootdirectory，此处为了quixote不抛异常
class HackRootDirectory(Directory):
    pass

class PynixWebPublisher(Publisher):
    def __init__(self, mapper, root_directory=None, logger=None, session_manager=None, config=None, **kwargs):
        if(root_directory==None):
            root_directory = HackRootDirectory()
        Publisher.__init__(self, root_directory, logger, session_manager, config, **kwargs)
        self.mapper = mapper
        
    def try_publish(self, request):
        """(request : HTTPRequest) -> object

        The master method that does all the work for a single request.
        Exceptions are handled by the caller.
        """
        self.start_request()
        path = request.get_environ('PATH_INFO', '')
        if path[:1] != '/':
            return redirect(
                request.get_environ('SCRIPT_NAME', '') + '/' + path,
                permanent=True)
        action = path[:path.rfind('/')]
        if(action==''):
            action = '/'
        if(self.mapper.has_key(action)):
            controller = self.mapper[action]
            components = path.split('/')[-1:]
            output = controller._q_traverse(components)
            self.finish_successful_request()
            return output
        else:
            raise PublishError